package com.sgb.capital.view.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sgb.capital.R;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.databinding.OrderFragmentBinding;
import com.sgb.capital.model.Bean;
import com.sgb.capital.model.PayDetailEntity;
import com.sgb.capital.model.PayOrderBean;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.PayDetailPop;
import com.sgb.capital.view.pop.SelectPop;
import com.sgb.capital.view.pop.TipPop;
import com.sgb.capital.view.ui.activity.NewOrderPayActivity;
import com.sgb.capital.view.ui.adapter.FinanceFlowItemAdapter;
import com.sgb.capital.view.ui.adapter.OrderPayAdapter;
import com.sgb.capital.view.widget.xrecyclerview.ZXRecyclerView;
import com.sgb.capital.viewmodel.PayOrderModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

/**
 * 作者:张磊
 * 日期:2021/4/16 0016
 * 说明:待付订单
 */
public class OrderFragment extends AppLazyFragment {
    public static final String TAG = "orderFragment";
    PayOrderModel mModel;
    private OrderFragmentBinding mBinding;
    private FinanceFlowItemAdapter mFlowItemAdapter;
    private List<Bean> mOrderTypeBeans = new ArrayList<>();
    private List<Bean> mTimeBeans = new ArrayList<>();
    private List<Bean> mStatusBeans = new ArrayList<>();
    private TextView mTextView;
    private ImageView mImg;
    private OrderPayAdapter mOrderPayAdapter;
    private SelectPop mSelectPop;
    private PayDetailPop payDetailPop;
    private PayOrderBean mOrderBean = new PayOrderBean();
    private List<Bean> dataBeans = new ArrayList<>();
    private TipPop mTipPop;
    private String mTime;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.order_fragment, container, false);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (getActivity() instanceof NewOrderPayActivity) {
            NewOrderPayActivity activity = (NewOrderPayActivity) getActivity();
            mBinding.llShow.setVisibility(activity.mIsPayOrder ? View.GONE : View.VISIBLE);
        }
        mTipPop = new TipPop(getActivity());
        mModel = new ViewModelProvider(this).get(PayOrderModel.class);
        // TODO: 2021/4/20 0020 选项
        mBinding.rvItem.setLayoutManager(new GridLayoutManager(Utils.getContext(), 3));
        mFlowItemAdapter = new FinanceFlowItemAdapter(null);
        mBinding.rvItem.setAdapter(mFlowItemAdapter);
        // TODO: 2021/4/20 0020 列表
        mOrderPayAdapter = new OrderPayAdapter(getActivity(), null, new OrderPayAdapter.OnClickAdapterListener() {
            @Override
            public void OnItemClickPay(int index) {
                if (TextUtils.isEmpty(mOrderPayAdapter.getDatas().get(index).orderId)) {
                    mTipPop.initStr("订单异常,无法付款", null, "确定");
                    mTipPop.show();
                    return;
                }
                new TipPop(mActivity, "温馨提示", "企业用户仅支持B2B网银支付,请前往PC端进行操作", null, "确定").show();
                //  mModel.payInfo(mActivity, mOrderPayAdapter.getDatas().get(index).orderId);
            }

            @Override
            public void OnItemClickDetail(int index) {
                mModel.getPayOrderDetails(mActivity, mOrderPayAdapter.getDatas().get(index).orderId);
            }
        });
        mBinding.rvList.setLayoutManager(new GridLayoutManager(Utils.getContext(), 1));
        mBinding.rvList.setAdapter(mOrderPayAdapter);
        // TODO: 2021/4/21 0021 弹框及数据
        mSelectPop = new SelectPop(getActivity());
        mSelectPop.setBgView(mBinding.grayLayout);
        payDetailPop = new PayDetailPop(getActivity());
        payDetailPop.setBgView(mBinding.grayLayout);
    }


    @Override
    public void initObserve() {
        mModel.mBean.observe(this, beans -> {
            Bean bean = new Bean("全部");
            bean.value = "";
            mOrderTypeBeans.add(bean);
            mOrderTypeBeans.addAll(beans);
            mSelectPop.mType = 1;
            mSelectPop.setData(mOrderTypeBeans);
            mSelectPop.mAdapter.setDefItem(mSelectPop.mPos1);
            mSelectPop.showPopwindow(mBinding.view, 0, 0);
        });
        mModel.mPayInfo.observe(this, payInfoEntity -> {
            if (payInfoEntity == null) {
                new TipPop(mActivity, "温馨提示", "订单异常，无法付款", null, "确定").show();
            } else {
                new TipPop(mActivity, "温馨提示", "企业用户仅支持B2B网银支付,请前往PC端进行操作", null, "确定").show();
                //  CheckoutCounterActivity.start(mActivity, new Gson().toJson(payInfoEntity), 100, false);
            }
        });
        mModel.payDetails.observe(this, payDetails -> showDetailPop(payDetails));
        mModel.mPayOrderList.observe(this, payOrderEntities -> {
            if (mOrderBean.page != 1) {
                mBinding.rvList.loadMoreComplete();
                if (payOrderEntities.size() != 0) {
                    mOrderPayAdapter.addDatas(payOrderEntities);
                } else {
                    mBinding.rvList.setNoMore(true);
                }
            } else {
                mBinding.errorView.setVisibility(payOrderEntities.size() != 0 ? View.GONE : View.VISIBLE);
                mBinding.rvList.refreshComplete();
                mBinding.rvList.setLoadingMoreEnabled(true);
                mOrderPayAdapter.setDatas(payOrderEntities);
            }
        });
    }

    @Override
    protected void onLazyLoad() {
        Bundle arguments = getArguments();
        String data = arguments.getString("data");
        List<Bean> beans = new ArrayList<>();
        beans.add(new Bean("订单类型"));
        beans.add(new Bean("申请时间"));
        if (data.contains("待支付")) {
            beans.add(new Bean("付款状态"));
        }
        mOrderBean.state = data.contains("待支付") ? "1" : "5";
        mFlowItemAdapter.setNewInstance(beans);
        Utils.setBeans(mTimeBeans, new String[]{"全部", "今日", "最近一周", "最近一个月", "最近一年"});
        Utils.setBeans(mStatusBeans, new String[]{"全部", "未付款"});
        mModel.getPayOrderList(mActivity, mOrderBean);
    }

    @Override
    public void initListener() {
        mBinding.etSs.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                mOrderBean.page = 1;
                mOrderBean.orderId = mBinding.etSs.getText().toString().trim();
                mModel.getPayOrderList(mActivity, mOrderBean);
            }
            return false;
        });
        mBinding.rvList.setLoadingListener(new ZXRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mOrderBean.page = 1;
                mModel.getPayOrderList(mActivity, mOrderBean);
            }

            @Override
            public void onLoadMore() {
                mOrderBean.page++;
                mModel.getPayOrderList(mActivity, mOrderBean);
            }
        });
        mSelectPop.setOnDismissListener(() -> {
            mImg.setRotation(0);
            if (mSelectPop.mType == 1 && mSelectPop.mPos1 == 0) {
                mOrderBean.orderType = null;
                setStyle(mTextView, "订单类型");
                mImg.setImageResource(R.mipmap.ic_down_arrow_n);
            } else if (mSelectPop.mType == 2 && mSelectPop.mPos2 == 0) {
                setStyle(mTextView, "申请时间");
                mImg.setImageResource(R.mipmap.ic_down_arrow_n);
                mOrderBean.startTime = null;
                mOrderBean.endTime = null;
            } else if (mSelectPop.mType == 3 && mSelectPop.mPos3 == 0) {
                setStyle(mTextView, "付款状态");
                mImg.setImageResource(R.mipmap.ic_down_arrow_n);
                mOrderBean.state = null;
            } else {
                if (mSelectPop.mIsClick) {
                    mTextView.setText(mSelectPop.mBean.name);
                    if (mSelectPop.mType == 1) {
                        mOrderBean.orderType = mSelectPop.mBean.value;
                    } else if (mSelectPop.mType == 3) {
                        mOrderBean.state = "1";
                    } else {
                        mTime = mSelectPop.mBean.name.contains("今日") ? Utils.getStartAndEndTime(0, 0, "今日")
                                : mSelectPop.mBean.name.contains("最近一周") ? Utils.getStartAndEndTime(1, 7, "最近一周")
                                : mSelectPop.mBean.name.contains("最近一个月") ? Utils.getStartAndEndTime(2, 1, "最近一个月")
                                : Utils.getStartAndEndTime(3, 1, "最近一年");
                        mOrderBean.startTime = mTime.split("-")[0];
                        mOrderBean.endTime = mTime.split("-")[1];
                    }
                    mTextView.setTextColor(Utils.getColor(mSelectPop.mType == 1 ?
                            mSelectPop.mPos1 != 0 ? R.color.color_EF4033 : R.color.color_333333 :
                            mSelectPop.mType == 2 ? mSelectPop.mPos2 != 0 ? R.color.color_EF4033 : R.color.color_333333 :
                                    mSelectPop.mPos3 != 0 ? R.color.color_EF4033 : R.color.color_333333
                    ));
                    mImg.setImageResource(mSelectPop.mType == 1 ? mSelectPop.mPos1 != 0 ?
                            R.mipmap.down : R.mipmap.ic_down_arrow_n : mSelectPop.mType == 2 ?
                            mSelectPop.mPos2 != 0 ? R.mipmap.down : R.mipmap.ic_down_arrow_n :
                            mSelectPop.mPos3 != 0 ? R.mipmap.down : R.mipmap.ic_down_arrow_n
                    );
                }
            }
            if (mSelectPop.mIsClick) {
                mSelectPop.mIsClick = false;
                mOrderBean.page = 1;
                mModel.getPayOrderList(mActivity, mOrderBean);
            }
        });
        mFlowItemAdapter.setOnItemClickListener((adapter, view, position) -> {
            Utils.hide(mActivity);
            LinearLayout linearLayout = (LinearLayout) view;
            mTextView = (TextView) linearLayout.getChildAt(0);
            mImg = (ImageView) linearLayout.getChildAt(1);
            mImg.setRotation(180);
            switch (position) {
                case 0:
                    if (mOrderTypeBeans.size() == 0) {
                        mModel.getOrderType(mActivity);
                        return;
                    }
                    mSelectPop.mType = 1;
                    mSelectPop.setData(mOrderTypeBeans);
                    mSelectPop.mAdapter.setDefItem(mSelectPop.mPos1);

                    break;
                case 1:
                    mSelectPop.mType = 2;
                    mSelectPop.setData(mTimeBeans);
                    mSelectPop.mAdapter.setDefItem(mSelectPop.mPos2);
                    break;
                case 2:
                    mSelectPop.mType = 3;
                    mSelectPop.setData(mStatusBeans);
                    mSelectPop.mAdapter.setDefItem(mSelectPop.mPos3);
                    break;
            }
            mSelectPop.showPopwindow(mBinding.view, 0, 0);
        });
    }

    private void showDetailPop(PayDetailEntity payDetailEntity) {
        dataBeans.clear();
        dataBeans.add(new Bean("订单类型", payDetailEntity.orderTypeName));
        dataBeans.add(new Bean("订单号", payDetailEntity.paymentId));
        dataBeans.add(new Bean("业务支付号", payDetailEntity.orderId));
        dataBeans.add(new Bean("交易流水号", payDetailEntity.number));
        dataBeans.add(new Bean("付款方式", payDetailEntity.method));
        dataBeans.add(new Bean("支付类型", payDetailEntity.payType));
        dataBeans.add(new Bean("支付渠道", payDetailEntity.channel));
        dataBeans.add(new Bean("付款账户", payDetailEntity.account));
        dataBeans.add(new Bean("付款账号", payDetailEntity.accountNumber));
        dataBeans.add(new Bean("交易金额", payDetailEntity.money));
        String status = "";
        if (payDetailEntity.payState == 0) status = "未付款";
        if (payDetailEntity.payState == 1) status = "冻结中";
        if (payDetailEntity.payState == 2) status = "支付成功";
        if (payDetailEntity.payState == 3) status = "支付失败";
        String status2 = "";
        if (payDetailEntity.state == 0) status2 = "审批中";
        if (payDetailEntity.state == 1) status2 = "审批通过";
        if (payDetailEntity.state == 3) status2 = "审批未通过";
        if (payDetailEntity.state == 4) status2 = "确认中";
        if (payDetailEntity.state == 5) status2 = "支付成功";
        dataBeans.add(new Bean("交易状态", status));
        dataBeans.add(new Bean("付款状态", status2));
        dataBeans.add(new Bean("创建时间", Utils.getTime(payDetailEntity.created)));
        dataBeans.add(new Bean("完成时间", Utils.getTime(payDetailEntity.completionTime)));
        payDetailPop.setData(dataBeans);
        payDetailPop.showDownPopwindow(mBinding.grayLayout, true);
    }


    private void setStyle(TextView textView, String title) {
        textView.setText(title);
        textView.setTextColor(Utils.getColor(R.color.color_333333));
    }


    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    @Subscribe
    public void getCode(ZMessageEvent event) {
        switch (event.code) {
            case Constants
                    .EVENT_REFRESH:
                mOrderBean.page = 1;
                mModel.getPayOrderList(mActivity, mOrderBean);
                break;
        }
    }


}